package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 定时关闭超时未支付的订单
     */
    @Scheduled(cron = "0/30 * * * * ?") //每隔30s执行一次
    public void cancelOrder(){
        //1. 查询符合条件(待支付 , 15分钟之前下单)的订单
        LocalDateTime before15Time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList =  ordersMapper.selectByStatusAndLtTime(Orders.ORDER_STAUTS_PENDING_PAYMENT, before15Time);

        //2. 如果存在这样的订单 , 取消订单 - 修改订单状态
        if(!CollectionUtils.isEmpty(ordersList)){
            ordersList.stream().forEach(orders -> {
                log.info("执行定时取消订单的操作 , {}", orders.getId());
                //取消订单
                orders.setStatus(Orders.ORDER_STAUTS_CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("支付超时, 系统自动取消");
                ordersMapper.update(orders);
            });
        }

    }



    /**
     * 定时完成订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0 25 12 * * ?")
    public void completeOrder(){
        //1. 查询符合条件(派送中 , 2小时之前下单)的订单
        LocalDateTime before2HourTime = LocalDateTime.now().minusHours(2);
        List<Orders> ordersList =  ordersMapper.selectByStatusAndLtTime(Orders.ORDER_STAUTS_DELIVERY_IN_PROGRESS, before2HourTime);

        //2. 如果存在这样的订单 , 完成订单 - 修改订单状态
        if(!CollectionUtils.isEmpty(ordersList)){
            ordersList.stream().forEach(orders -> {
                log.info("执行定时完成订单的操作 , {}", orders.getId());

                orders.setStatus(Orders.ORDER_STAUTS_COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                ordersMapper.update(orders);
            });
        }
    }

}
